import httpService, { RequestParam } from './request';
import http from '@ohos.net.http';
import { fileManager } from "../utils/fileUtils"
import { strCaptions } from '../utils/recallInterface';
import { promptAction } from '@kit.ArkUI';
import AccessibilityUtils from '../AccessibilityExtAbility/AccessibilityUtils';
import { sleep } from '../utils/DateTimeUtil';

let SUBMIT_URL =
  "https://aip.baidubce.com/rpc/2.0/wenxin/v1/extreme/textToImage?access_token=24.6396bb09dcae4ad7ea375465bdb9e05b.2592000.1737641754.282335-116302661"
let QUERY_URL =
  "https://aip.baidubce.com/rpc/2.0/wenxin/v1/extreme/getImg?access_token=24.6396bb09dcae4ad7ea375465bdb9e05b.2592000.1737641754.282335-116302661"

// GENERATION_URL="http://192.168.227.230:5000/post-endpoint"
let TAG = "_:_ImageRecog"

export default class ImageRecogManager {
  private ImgGenresult

  InitParam(jstr) {
    return {
      method: http.RequestMethod.POST,
      header: [{
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      }],
      extraData: jstr
    }
  }

  parseIGResult(result, parseFun) {
    let TAG = "_:_[parseResultImgGen]"
    console.log(TAG, "rawresult is ", result)
    if (result.includes("error_msg")) {
      promptAction.showToast({
        "message": result,
        "duration": 5000
      })
      return "-1"
    }
    try {
      let resultj = JSON.parse(result)
      console.log(TAG, "parse success ", resultj, JSON.stringify(resultj))
      return parseFun(resultj)
    } catch (e) {
      console.error(TAG, "parseResult", e)
      return result
    }
  }

  async Submit(promptStr): Promise<string> {
      promptStr=promptStr.slice(0,30)
    let submitParam = this.InitParam(JSON.stringify({
      "prompt": promptStr.replace(/\n/g, ""),
      "width": 512,
      "height": 512
    }))
    let task_id = await httpService.requestMain(SUBMIT_URL, submitParam, (response) => {
      return this.parseIGResult(response, (obj) => {
        return obj["data"]["task_id"]
      })
    })
    return task_id
  }

  async GetProgress(task_id): Promise<number> {
    let queryParam = this.InitParam(JSON.stringify({
      "task_id": task_id
    }))
    let progress = await httpService.requestMain(QUERY_URL, queryParam, (response) => {
      return this.parseIGResult(response, (obj) => {
        return obj["data"]["task_progress"]
      })
    })
    return progress
  }

  async getImg(task_id): Promise<string> {
    let queryParam = this.InitParam(JSON.stringify({
      "task_id": task_id
    }))
    let url = await httpService.requestMain(QUERY_URL, queryParam, (response) => {
      return this.parseIGResult(response, (obj) => {
        return obj["data"]["sub_task_result_list"][0]["final_image_list"][0]["img_url"]
      })
    })
    return url
  }

  async getImgRepeat(task_id): Promise<string> {
    let progress = await this.GetProgress(task_id)
    while (progress != 1) {
      await sleep(1000)
      progress = await this.GetProgress(task_id)
    }
    return await this.getImg(task_id)
  }
}